import React from 'react';
import {  Button, Table, Form, Modal, Pagination } from 'antd';
import './index.less';
import axios from 'axios';
import Tips from '../Tips/index';
import { connect } from 'react-redux';
import statuscode from '../statuscode/index';
import Addpeer from './AddPeer/index.jsx';
import ExtendPeer from './extend/index.jsx';
import Bread from '../common/Bread/index';
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';

const peerStatus = {
  1000: '创建中',
  1010: '创建成功',
  1020: '创建失败',
};
class peer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      page: ['1', '2', '10', '20', '30', '40', '50', '60', '70', '80', '90'],
      message: '',
      limit: 10,
      pagenum: 1,
      timeout: false,
      netWorkName: this.props.changeNetwork,
      addvisible: false,
      extendvisible: false,
      tipvisible: false
    };
  }
  columns = [
    {
      title: '节点名称',
      dataIndex: '节点名称',
      key: '节点名称'
    },
    {
      title: '地址',
      dataIndex: '地址',
      key: '地址'
    },
    {
      title: '状态',
      dataIndex: '状态',
      key: '状态'
    },
    {
      title: '端口',
      dataIndex: '端口',
      key: '端口'
    }
  ];
  componentWillMount() {
    this.ismounted = true;
    this.getData();
  }
  componentWillUnmount() {
    this.ismounted = false;
  }

  handleChancel = () => {
    this.setState({
      addvisible: false
    });
  };
  extendChancel = () => {
    this.setState({
      extendvisible: false
    });
  };
  extendsubmit = (qq, values) => {};
  showModal = () => {
    this.setState({ message: 'loading' });
    const $this = this;
    var data = { networkName: this.props.changeNetwork, orgId: this.props.changeOrgid };
    const Token = localStorage.getItem('token');
    axios
      .post('/api/block/network/checkNetworkAdmin', data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: Token
        }
      })
      .then(function(response) {
        if ($this.ismounted) {
          var code = response.data.code;
          if (statuscode[response.data.code] == undefined) code = 500;
          var message = statuscode[code];
          if (response.data.data == false) message = '您不是网络管理员！';
          $this.setState({ message: message }, () => {
            if (response.data.data) {
              $this.setState({
                addvisible: true
              });
            }
          });
        }
      })
      .catch(function(error) {
        console.log(error);
        if ($this.ismounted) {
          $this.setState(
            { message: '请求失败，请刷新重试' },
            () => {
              setTimeout(() => {
                $this.setState({ message: '' });
              }, 1000);
            }
          );
        }
      });
  };

  usepeer = (text, record) => {};
  stoppeer = (text, record) => {};
  extendpeer = (text, record) => {
    this.setState({
      extendvisible: true
    });
  };
  componentWillReceiveProps(nextprops) {
    if (this.props.changeNetwork !== nextprops.changeNetwork) {
      this.getData(nextprops.changeNetwork);
    }
  }
  tipCancel = () => {
    this.setState({ tipvisible: false });
  };

  onShowSizeChange = (current, pageSize) => {
    this.setState({ limit: pageSize, pagenum: current }, () => {
      this.getData(this.props.changeNetwork);
    });
  };
  addsubmit = (qq, values) => {
    const $this = this;
    this.setState({ message: 'loading' });
    var data = { networkName: this.props.changeNetwork, orgId: this.props.changeOrgid };
    const Token = localStorage.getItem('token');
    axios
      .post('/api/block/peer/addPeer', data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: Token
        }
      })
      .then(function(response) {
        if ($this.ismounted) {
          var code = response.data.code;
          if (statuscode[response.data.code] == undefined) code = 500;
          var message = statuscode[code];
          $this.setState({ message: message }, () => {
            setTimeout(() => {
              $this.setState({ addvisible: false, tipvisible: true });
            }, 1000);
          });
        }
      })
      .catch(function(error) {
        console.log(error);
        if ($this.ismounted) {
          $this.setState({ message: '请求失败，请刷新重试' }, () => {
            setTimeout(() => {
              $this.setState({ message: '' });
            }, 1000);
          });
        }
      });
  };

  onChange = pageNumber => {
    this.setState({ pagenum: pageNumber }, () => {
      this.getData(this.props.changeNetwork);
    });
  };
  getData = (Network = this.props.changeNetwork) => {
    var _this = this;
    var Token = localStorage.getItem('token');
    if (!Network) {
      this.setState({
        data: [],
        totalnum: 0,
        messgae: ''
      });
      return;
    }
    this.setState({
      message: 'loading'
    });
    const $this = this;
    var url = Number(this.props.changSandBox) ? 'api/block/peer/queryPeer' : 'api/sandbox/fabric/queryPeer';
    axios({
      method: 'get',
      url: url,
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token
      },
      params: {
        RequestType: 'QueryAllPeerReq',
        FabricFlag: Network,
        channelId: 'mychannel',
        //   limit: this.state.limit,
        //   page: this.state.pagenum,
        orgId: this.props.changeOrgid
      }
    })
      .then(function(response) {
        if (_this.ismounted) {
          let data = [];
          var code = response.data.code;
          // if (statuscode[response.data.code] == undefined) code = 500
          var message = statuscode[code];
          _this.setState({ message: message }, () => {
            setTimeout(() => {
              _this.setState({ message: '' });
            }, 1000);
          });
          let responsedata =
            response.data && response.data.data ? response.data.data : null;
          responsedata &&
            responsedata.forEach((e, i) => {
              data.push({
                key: String(i),
                节点名称: e.ServerName,
                地址: e.Host,
                端口: e.Port,
                状态: peerStatus[e.Status]
              });
            });
          $this.setState({
            data: data,
            totalnum:
              response.data && response.data.data
                ? response.data.data.length
                : 0,
            messgae: ''
          });
        }
      })
      .catch(function(error) {
        if (_this.ismounted) {
          var message = '请求失败，请刷新重试';
          if (error === []) message = '';
          _this.setState({ message: message }, () => {
            setTimeout(() => {
              _this.setState({ message: '' });
            }, 1000);
          });
        }
      });
  };
  tipOK= () => {
    this.setState({ tipvisible: false });
    this.getData();
  }

  render() {
    const { selectedRowKeys, selectStatus } = this.state;
    const rowSelection = {
      selectedRowKeys,
      type: 'radio',
      onChange: this.onSelectChange
    };
    const ButtonType = selectStatus ? 'default' : 'primary';
    const disabled = selectStatus ? 'disabled' : '';
    return (
      <div>
        <Bread bread={['节点管理', ['节点管理', 'nenodeManaget']]} />
        {/* <span className='ChainCode_button'> */}
        <div className="index-buttons chaincodebuttons">
          <Button
            type="primary"
            onClick={this.showModal}
            disabled={this.props.changeOrgid && Number(this.props.changSandBox) ? false : true}
          >
            新建Peer
          </Button>
        </div>
        <Table
          // rowSelection={rowSelection}
          columns={this.columns}
          dataSource={this.state.data}
          bordered
          pagination={false}
        />
        <div className="page_foot">
          {/* <span className="data_num">共{this.state.totalnum}条</span> */}
          {/* <Pagination pageSizeOptions={this.state.page}  className="page" showSizeChanger showQuickJumper onShowSizeChange={this.onShowSizeChange} defaultCurrent={1} total={this.state.totalnum} onChange={this.onChange} /> */}
        </div>
        <Addpeer
          visible={this.state.addvisible}
          onCancel={this.handleChancel}
          addsubmit={this.addsubmit}
        />
        <ExtendPeer
          visible={this.state.extendvisible}
          onCancel={this.extendChancel}
          submit={this.extendsubmit}
        />
        <Tips message={this.state.message} />
        <Modal
          style={{ zIndex: 1000 }}
          closable={false}
          visible={this.state.tipvisible}
          title="新建Peer请求提交成功"
          iconType="warning"
          onCancel={this.tipCancel}
          footer={[
            // <Button key="back" onClick={this.handleCancel}>取消</Button>,
            <Button key="submit" type="primary" onClick={this.tipOK}>
              确定
            </Button>
          ]}
        >
          <p className="" style={{ textAlign: 'center', marginBottom: 0 }}>
            <span>您的新建Peer请求已经成功提交到Fabric网络，</span>
            <br />
            <span> 请在10分钟以后在列表中查看新建Peer节点信息。</span>
          </p>
        </Modal>
      </div>
    );
  }
}

const Peer = Form.create()(peer);

export default connect((state) => {
  return { ...state };
})(Peer);
